package com.jplus.core.utill.serializer;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jplus.core.utill.serializer.impl.JavaSerializer;

/**
 * 对象序列化工具包
 * 
 * @author yuanqy
 */
public class SerializationUtil {

	private final static Logger log = LoggerFactory.getLogger(SerializationUtil.class);
	private static Serializer def_ser;

	public static enum STYPE {
		JAVA, FST, KRYO, KRYO_POOL_SER, CUSTOM, OTHER;
	}

	private static Map<STYPE, Serializer> serKit = new HashMap<>();

	public static void addSerializKit(STYPE STYPE, Class<? extends Serializer> serializer) {
		try {
			Serializer instance = serializer.newInstance();
			serKit.put(STYPE, instance);
			def_ser = instance;
		} catch (Exception e) {
			log.error("addSerializKit ERROR:", e);
		}
	}

	static {
		// 默认使用java原生序列化方式
		addSerializKit(STYPE.JAVA, JavaSerializer.class);
	}

	public static byte[] serialize(Object obj) throws IOException {
		return def_ser.serialize(obj);
	}

	public static Object deserialize(byte[] bytes) throws IOException {
		return def_ser.deserialize(bytes);
	}

	public static byte[] serialize(STYPE type, Object obj) throws IOException {
		return serKit.get(type).serialize(obj);
	}

	public static Object deserialize(STYPE type, byte[] bytes) throws IOException {
		return serKit.get(type).deserialize(bytes);
	}
}
